/**
 * 此js不能含有v14s函数，因为这里的有些函数需要应用于config.js，在国际化接口请求之前就加载
 * =================
 */
import Variables from '@/common/variables.js';
import { isEqual, isObject, transform } from 'lodash';

export const objHas = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);

// 获取url传参
export const getQueryValue = name => {
  const reg = new RegExp(`${name}=([^&]*)(&|$)`, 'i');
  const r = window.location.href.match(reg);
  if (r !== null) {
    return unescape(r[1]);
  }
  return null;
};

// 获取缩放比率：rateW, rateH, rate
export const getWinRates = type => {
  const _vue = window.xVueWeb.app.config.globalProperties;
  let rateW = Number(_vue.$xvueZipWRate) || 1;
  let rateH = Number(_vue.$xvueZipHRate) || 1;

  if (window.isLocalEnv) {
    let winWidth = window.innerWidth;
    let winHeight = window.innerHeight;
    winWidth = winWidth < 1280 ? 1280 : winWidth;
    winHeight = winHeight < 768 ? 768 : winHeight;
    rateW = innerWidth / 1920;
    rateH = innerHeight / 1080;
  }

  let rate = rateW > rateH ? rateH : rateW;
  if (rate > 1) {
    // 遵循原逻辑，即宽度大于1920，使用1920
    rate = 1;
  }

  const obj = { rateW, rateH, rate };
  if (!type) {
    return obj;
  }
  return obj[type];
};

// 获取公共值
export const getCommonVal = (key, componentStyle) => {
  let _componentStyle;
  if (!componentStyle) {
    _componentStyle = (window.isLocalEnv && getQueryValue('componentStyle')) || window._adoPremise.uc.theme;
  } else {
    _componentStyle = componentStyle;
  }

  const keys = key.split('.');
  let val = Variables;
  for (let i = 0; i < keys.length; i++) {
    val = val[keys[i]];
  }

  if (typeof val === 'object' && objHas(val, _componentStyle)) {
    val = val[_componentStyle];
  }
  return val;
};

/*
 * 根据下标路径获取变量子孙属性值
 * 例子： getVarChildVar({a:{b:[1,2]}}, 'a.b[1]') => 2
 */
export const getVarChildVal = (variable, keyPath) => {
  const _keyPath = keyPath.replace(/\[/g, '.').replace(/\]/g, '');
  const keyArr = _keyPath.split('.');
  let _variable = variable;
  for (let i = 0; i < keyArr.length; i++) {
    _variable = _variable[keyArr[i]];
    if (typeof _variable === 'undefined') {
      break;
    }
  }
  return _variable;
};

// 对象对比相减，适用于对象，二维数组
export const objDiff = (obj, base) => {
  function diff(_obj, _base) {
    return transform(_obj, (result, value, key) => {
      if (!isEqual(value, _base[key])) {
        result[key] = isObject(value) && isObject(_base[key]) ? diff(value, _base[key]) : value;
      }
    });
  }
  return diff(obj, base);
};

// 获取页面pageId值
export const getPageId = vm => {
  if (window.isLocalEnv) {
    // 本地环境
    return 'local_pageid';
  }

  // 其他环境
  if (vm && vm.curPageId) {
    return vm.curPageId;
  }

  if (
    window._xvueStore &&
    window._xvueStore.state &&
    window._xvueStore.state.xvueWidgetLayout &&
    window._xvueStore.state.xvueWidgetLayout.pageId
  ) {
    return window._xvueStore.state.xvueWidgetLayout.pageId;
  }
  return '';
};
